﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using LuckyBingoRcon.Commands.Events;

namespace LuckyBingoRcon.Commands
{
	public class ServerVarsCommand : Command
	{
		public EventHandler<ServerVarsCommandEventArgs> OnResponse;
        
        public ServerVarsCommand(bool setCommand)
        {
            if (!setCommand)
                base.commandText = "dvardump";
            else
                base.commandText = "setadmindvar ";
            base.args = null;
        }

		protected override void CommandOnResponse(string response)
		{
			Dictionary<string, string> vars = new Dictionary<string, string>();
			StringReader sr = new StringReader(response);
			string[] delims = new string[] { " ", "^7" };
			bool foundDvars = false;

			try
			{
				while (sr.Peek() > -1)
				{
					string ln = sr.ReadLine().Trim();
					if (!String.IsNullOrEmpty(ln) && foundDvars)
					{
						string[] args = ln.Split(delims, 2, StringSplitOptions.RemoveEmptyEntries);
						if (args.Length >= 2)
							vars.Add(args[0], args[1].Replace("\"", ""));
					}
					if (ln.Contains("DVAR DUMP"))
						foundDvars = true;
				}

				if (OnResponse != null)
				{
					ServerVarsCommandEventArgs e = new ServerVarsCommandEventArgs();
					if (foundDvars)
						e.ServerVariables = vars;
					else
						e.ServerVariables = null;
					OnResponse(this, e);
				}
			}
			catch (Exception error)
			{
				if (OnResponse != null)
				{
					ServerVarsCommandEventArgs e = new ServerVarsCommandEventArgs();
					e.Error = error;
					if (foundDvars)
						e.ServerVariables = vars;
					else
						e.ServerVariables = null;
					OnResponse(this, e);
				}
			}

			sr.Close();
		}

        public override string ToString()
        {
            if (base.commandText.Contains("setadmindvar"))   // Is a set command
                return "Set\t" + base.args[0] + "\t=\t" + base.args[1];
            else
                return "Get\tServer Variables";
        }
	}
}
